const carts ={
  state:{
    cart:localStorage["cart"]?JSON.parse(localStorage["cart"]):[], //购物车
    all_money:0, //总价
    all_selsect:true //全选状态
  },
  //同步
  mutations:{
    //添加商品
    ADDGoods(state,data){
      let datas = {
        title:data.productName,
        img:data.img,
        numbers:data.num,
        sellPrice:data.price,
        selected:true,
        id:data.id
      }
      let index=-1
      index = state.cart.findIndex(item=>{
        return item.id == data.id
      })
      if(index==-1){
        state.cart.push(datas)
      }else{
        state.cart[index].numbers += data.num
      }
    },
    //购物车页面数量加减
    ADDNUM(state,productId){
      let index=state.cart.findIndex(item=>{
        return item.id==productId
     })
    return state.cart[index].numbers++
    },
    //购物车页面数量加减
    JIANNUM(state,productId){
      let index=state.cart.findIndex(item=>{
          return item.id==productId
        })
      if(state.cart[index].numbers<=1){
          return state.cart[index].numbers=1
      }else{
          return state.cart[index].numbers--
      }
    },
    //删除选中的商品，注意这里不能使用数组删除的方法，索引值会有问题
    DEL(state){
      let flag=state.car.some((item)=>{
          return item.selected==true
      })
      if(!flag){
          Toast.text('请至少选择一个商品')
      }else{
        Dialog[0]({
            title:'确定从购物车中删除吗？',
            onOkBtn() {  //确定按钮点击事件
                this.close(); //关闭对话框
                var list=[];
                state.car.forEach((item,index)=>{
                    if(!item.selected){
                        list.push(item)
                    }
                })
                return state.car=list
            },
        })
      }
    },
    CLEAR(state,data){
      state.cart = data
    }
  },
  //异步
  actions:{
    addGoods({commit},data){
      commit('ADDGoods',data)
    },
    addNum({commit},id){
        commit('ADDNUM',id)
    },
    jianNum({commit},id){
      commit('JIANNUM',id)
    },
    del({commit}){
      commit('DEL')
    },
    clearCart({commit},data){
      commit('CLEAR',data)
    }
  }

}


export default carts;